const app = getApp()
const appointmentService = require('../../../services/appointment');
const consultService = require('../../../services/consult');
const medicalService = require('../../../services/medical');

Page({
  data: {
    appointment: null,
    loading: true,
    statusIcons: {
      waiting: '/images/clock.png',
      confirmed: '/images/confirmed.png',
      completed: '/images/completed.png',
      cancelled: '/images/cancelled.png'
    },
    statusTitles: {
      waiting: '等待确认',
      confirmed: '已确认',
      completed: '已完成',
      cancelled: '已取消'
    },
    statusDescs: {
      waiting: '预约待确认，请尽快处理',
      confirmed: '预约已确认，请按时接诊',
      completed: '预约已完成',
      cancelled: '预约已取消'
    }
  },

  onLoad(options) {
    const appointmentId = options.id
    if (appointmentId) {
      this.getAppointmentDetail(appointmentId)
    } else {
      wx.showToast({
        title: '预约ID不存在',
        icon: 'error'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  getAppointmentDetail(appointmentId) {
    this.setData({
      loading: true
    })
    
    appointmentService.getAppointmentDetail(appointmentId)
      .then(res => {
        console.log('获取预约详情成功:', res);
        
        // 检查用户名相关字段 
        console.log('用户ID:', res.userId);
        console.log('用户名字段:', res.username);
        console.log('用户名字段(userName):', res.userName);
        
        // 检查extraData字段
        if (res.extraData) {
          console.log('extraData字段:', res.extraData);
          console.log('extraData中的username:', res.extraData.username);
        } else {
          console.log('没有extraData字段');
        }
        
        this.setData({
          appointment: res,
          loading: false
        })
      })
      .catch(err => {
        console.error('获取预约详情失败', err);
        wx.showToast({
          title: err.message || '获取预约详情失败',
          icon: 'none'
        })
        this.setData({
          loading: false
        })
      });
  },

  // 确认预约
  handleConfirm() {
    this.updateAppointmentStatus('confirmed')
  },

  // 拒绝预约
  handleReject() {
    wx.showModal({
      title: '拒绝预约',
      content: '确定要拒绝此预约吗？',
      confirmText: '确定拒绝',
      confirmColor: '#FF5722',
      success: (res) => {
        if (res.confirm) {
          this.updateAppointmentStatus('cancelled')
        }
      }
    })
  },

  // 完成预约
  handleComplete() {
    this.updateAppointmentStatus('completed')
  },

  // 更新预约状态
  updateAppointmentStatus(status) {
    wx.showLoading({
      title: '处理中...',
      mask: true
    })

    let promise;
    if (status === 'confirmed') {
      promise = appointmentService.confirmAppointment(this.data.appointment.id);
    } else if (status === 'cancelled') {
      promise = appointmentService.rejectAppointment(this.data.appointment.id);
    } else if (status === 'completed') {
      promise = appointmentService.completeAppointment(this.data.appointment.id);
    } else {
      wx.hideLoading();
      wx.showToast({
        title: '不支持的状态操作',
        icon: 'none'
      });
      return;
    }

    promise.then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '操作成功',
        icon: 'success'
      })
      
      // 更新本地数据
      const appointment = this.data.appointment
      // 状态码映射：confirmed->1, completed->2, cancelled->3
      const statusMap = {
        'confirmed': 1,
        'completed': 2,
        'cancelled': 3
      };
      appointment.status = statusMap[status] || appointment.status;
      this.setData({
        appointment: appointment
      })
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err.message || '操作失败',
        icon: 'none'
      })
    });
  },

  // 联系用户
  handleContact() {
    if (!this.data.appointment || !this.data.appointment.userId) {
      wx.showToast({
        title: '无法获取用户信息',
        icon: 'none'
      })
      return
    }
    
    // 显示操作菜单
    wx.showActionSheet({
      itemList: ['发送消息', '拨打电话'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 发送消息 - 先创建或获取会话，然后跳转到聊天页面
          this.createOrGetConversation()
        } else if (res.tapIndex === 1) {
          // 拨打电话
          if (this.data.appointment && this.data.appointment.user && this.data.appointment.user.phone) {
            wx.makePhoneCall({
              phoneNumber: this.data.appointment.user.phone,
              fail: () => {
                wx.showToast({
                  title: '拨打电话失败',
                  icon: 'none'
                })
              }
            })
          } else {
            wx.showToast({
              title: '用户未提供联系方式',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  
  // 创建或获取会话
  createOrGetConversation() {
    wx.showLoading({
      title: '正在加载聊天...',
      mask: true
    })
    
    // 使用封装的consultService的正确方法名
    consultService.getOrCreateUserConversation(this.data.appointment.userId)
      .then(res => {
        wx.hideLoading()
        // 跳转到聊天页面
        this.navigateToChat(res.id || res)
      })
      .catch(err => {
        wx.hideLoading()
        wx.showToast({
          title: err.message || '创建会话失败',
          icon: 'none'
        })
      })
  },
  
  // 跳转到聊天页面
  navigateToChat(conversationId) {
    wx.navigateTo({
      url: `/pages/staff/consults/chat?id=${conversationId}`
    })
  },

  // 创建就诊记录
  handleCreateConsult() {
    if (!this.data.appointment) return
    
    wx.navigateTo({
      url: `/pages/staff/consultations/create?appointmentId=${this.data.appointment.id}`
    })
  },
  
  // 查看就诊记录
  viewConsultation(e) {
    const consultationId = e.currentTarget.dataset.id
    if (consultationId) {
      wx.navigateTo({
        url: `/pages/staff/consultations/detail?id=${consultationId}`
      })
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.appointment && this.data.appointment.id) {
      this.getAppointmentDetail(this.data.appointment.id)
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
    } else {
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 创建健康档案
   */
  createMedicalRecord() {
    if (!this.data.appointment) {
      wx.showToast({
        title: '获取预约信息失败',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.appointment.status !== 1 && this.data.appointment.status !== 2) {
      wx.showToast({
        title: '只能为已确认或已完成的预约创建健康档案',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.appointment.medicalRecordId) {
      // 如果已经有健康档案了，跳转到查看页面
      this.viewMedicalRecord();
      return;
    }
    
    // 跳转到创建健康档案页面
    wx.navigateTo({
      url: `/pages/staff/medical/create?appointmentId=${this.data.appointment.id}&petId=${this.data.appointment.petId}`
    });
  },
  
  /**
   * 查看健康档案
   */
  viewMedicalRecord() {
    if (!this.data.appointment || !this.data.appointment.medicalRecordId) {
      wx.showToast({
        title: '暂无健康档案',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/staff/medical/detail?id=${this.data.appointment.medicalRecordId}`
    });
  },
  
  /**
   * 联系用户
   */
  contactUser() {
    // 实现联系用户的逻辑
    if (!this.data.appointment) {
      wx.showToast({
        title: '获取预约信息失败',
        icon: 'none'
      });
      return;
    }
    
    // 可以跳转到聊天页面或拨打电话等
    wx.showModal({
      title: '联系用户',
      content: '是否前往聊天页面联系用户？',
      success: (res) => {
        if (res.confirm) {
          // 跳转到聊天页面
          wx.navigateTo({
            url: `/pages/staff/consults/chat?userId=${this.data.appointment.userId}`
          });
        }
      }
    });
  },
  
  /**
   * 创建咨询
   */
  createConsultation() {
    if (!this.data.appointment) {
      wx.showToast({
        title: '获取预约信息失败',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.appointment.status !== 1 && this.data.appointment.status !== 2) {
      wx.showToast({
        title: '只能为已确认或已完成的预约创建咨询',
        icon: 'none'
      });
      return;
    }
    
    // 跳转到创建咨询页面
    wx.navigateTo({
      url: `/pages/staff/consultations/create?appointmentId=${this.data.appointment.id}&petId=${this.data.appointment.petId}&userId=${this.data.appointment.userId}`
    });
  },
  
  /**
   * 确认预约
   */
  confirmAppointment() {
    if (!this.data.appointment.id) {
      wx.showToast({
        title: '预约ID不能为空',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '处理中...',
    });
    
    appointmentService.confirmAppointment(this.data.appointment.id)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '已确认预约',
          icon: 'success'
        });
        // 重新加载数据
        this.getAppointmentDetail(this.data.appointment.id);
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '操作失败',
          icon: 'none'
        });
      });
  },
  
  /**
   * 拒绝预约
   */
  rejectAppointment() {
    if (!this.data.appointment.id) {
      wx.showToast({
        title: '预约ID不能为空',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '处理中...',
    });
    
    appointmentService.rejectAppointment(this.data.appointment.id)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '已拒绝预约',
          icon: 'success'
        });
        // 重新加载数据
        this.getAppointmentDetail(this.data.appointment.id);
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '操作失败',
          icon: 'none'
        });
      });
  },
  
  /**
   * 完成预约
   */
  completeAppointment() {
    if (!this.data.appointment.id) {
      wx.showToast({
        title: '预约ID不能为空',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '处理中...',
    });
    
    appointmentService.completeAppointment(this.data.appointment.id)
      .then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '已完成预约',
          icon: 'success'
        });
        // 重新加载数据
        this.getAppointmentDetail(this.data.appointment.id);
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '操作失败',
          icon: 'none'
        });
      });
  }
}) 